﻿using JNPF.Logging;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json.Linq;
using PARK.BussinCache.Interfaces;
using PARK.Common.Helper;
using PARK.Dependency;
using PARK.DynamicApiController;
using PARK.TaskScheduler.Interfaces;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace PARK.TaskScheduler
{
    /// <summary>
    /// 设备状态更新任务
    /// </summary>
    [ApiDescriptionSettings(Tag = "AccCtlOnlineJob", Name = "accCtlOnlineJobtask", Order = 220)]
    [Route("api/[controller]")]
    public class AccCtlOnlineJobService : BackgroundService, IAccCtlOnlineJobService, IDynamicApiController, ITransient
    {
        private readonly SqlSugarScope _db;
        private readonly IUniubiSdkRepository _uniubiSdkRepository;

        public AccCtlOnlineJobService(
            ISqlSugarClient db, IUniubiSdkRepository uniubiSdkRepository)
        {
            _db = (SqlSugarScope)db;
            _uniubiSdkRepository = uniubiSdkRepository;
        }
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {

        }

        /// <summary>
        /// 启动自启动任务
        /// </summary>
        [NonAction]
        public async void StartTimerJob()
        {
            new LoggEx().Info("设备状态更新->队列开始执行...");
            CancellationToken stoppingToken = new CancellationToken();
            var _EffeDuration = PARK.App.Configuration["AccessSettings:UpEvtStatusTime"]; //间隔时长(毫秒)
            while (!stoppingToken.IsCancellationRequested)
            {
                await new TaskFactory().StartNew(() =>
                {
                    try
                    {
                        RunAccCtlOnlineQueue();
                    }
                    catch (Exception e)
                    {
                        new LoggEx().Info("设备状态更新,队列异常:=============失败=====" + e.Message);
                    }
                    //定时任务休眠
                    Thread.Sleep(int.Parse(_EffeDuration));//5分钟 //300000
                });
            }
        }

        [NonAction]
        void RunAccCtlOnlineQueue()
        {
            try
            {
                var Paras = new List<SugarParameter>();
                var evts = _db.Ado.GetDataTable("select ctlId, ctlSN, ctlName, LastOnLineTime,CompanyId,CompanyName from access_ctl where ISNULL(IsDeleted, 0) = 0");
                if (evts.Rows.Count > 0)
                {
                    for (int i = 0; i < evts.Rows.Count; i++)
                    {
                        var _deviceId = evts.Rows[i]["ctlId"].ToString();
                        var _deviceNo = evts.Rows[i]["ctlSN"].ToString();
                        var _companyId = evts.Rows[i]["CompanyId"].ToString();
                        //调用宇泛接口,查询设备
                        var _uniret = _uniubiSdkRepository.deviceSync(_deviceNo, _companyId);
                        if (!string.IsNullOrEmpty(_uniret.data))
                        {
                            //new LoggEx().Info("更新设备在线状态:" + _uniret.ToJson());
                            JObject data = _uniret.data.ToObject();
                            if (data["data"]["onlineState"] != null)
                            {
                                string OnLineTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                //更新解析状态
                                StringBuilder _upSql = new StringBuilder("update access_ctl set ");
                                _upSql.AppendFormat(" IsOnline={0}", data["data"]["onlineState"].ToString());
                                //当前在线
                                if (data["data"]["onlineState"].ToString() == "1")
                                {
                                    _upSql.AppendFormat(" ,LastOnLineTime='{0}'", OnLineTime);
                                }
                                _upSql.AppendFormat(" where ctlSN='{0}' and ctlId='{1}'", _deviceNo, _deviceId);
                                //new LoggEx().Info("更新设备在线状态:"+_upSql.ToString());
                                _db.Ado.ExecuteCommand(_upSql.ToString(), Paras);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                new LoggEx().errlog("处理设备状态更新,异常:" + ex.Message);
            }
        }
    }
}
